<template>
  <div>
    <!-- 新增：搜索框 -->
    <div class="search-section">
      <el-input
        v-model="searchId"
        placeholder="请输入申请编号"
        clearable
        style="width: 300px; margin-right: 10px;"
      />
      <el-input
        v-model="searchClubName"
        placeholder="请输入社团名"
        clearable
        style="width: 300px; margin-right: 10px;"
      />
      <el-input
        v-model="searchActivityName"
        placeholder="请输入活动名"
        clearable
        style="width: 300px; margin-right: 10px;"
      />
      <!-- <el-button type="primary" @click="searchApplications">搜索</el-button> -->
      <el-button type="primary" @click="resetSearch">重置</el-button>
      <!-- 导出按钮 -->
      <el-button @click="exportToExcel" type="success">导出 Excel</el-button>
    </div>
  </div>
  <div class="user-personal-applications">
    <el-table :data="paginatedApplications" style="width: 100%">
      <el-table-column
        prop="level"
        label="申请等级"
        :filters="applicationLevelFilters"
        :filter-method="filterApplicationLevel"
      >
        <template #default="{ row }">
          <span>{{ getApplicationLevel(row.typeCode) }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="id" label="申请编号" />
      <el-table-column
        prop="type"
        label="申请类型"
        :filters="applicationTypeFilters"
        :filter-method="filterType"
        filter-placement="bottom-end"
      >
        <template #default="{ row }">
          <el-tag :type="getApplicationTypeColor(row.type)">{{
            row.type
          }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="clubName" label="社团名" />
      <el-table-column prop="activityName" label="活动名" />
      <el-table-column
        prop="status"
        label="申请状态"
        :filters="statusFilters"
        :filter-method="filterStatus"
        filter-placement="bottom-end"
      >
        <template #default="{ row }">
          <el-tag :type="getStatusType(row.status)">{{ row.status }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="applyTime" label="申请时间" sortable>
        <template #header>
          <span>申请时间</span>
          <el-button type="text" @click="sortByApplyTime"
            ><el-icon>
              <sort v-if="sortOrder === 'descending'" />
              <sort-up v-else />
            </el-icon>
          </el-button>
        </template>
      </el-table-column>
      <el-table-column label="操作" fixed="right">
        <template #default="{ row }">
          <el-button size="small" @click="handleDetails(row)">详情</el-button>

        </template>
      </el-table-column>
    </el-table>

    <!-- 分页控件 -->
    <div class="pagination-section">
        <span class="record-count"> 共查询到 {{ totalApplications }} 条记录</span>
        <el-pagination
          background
          layout="prev, pager, next"
          :total="totalApplications"
          v-model:page-size="pageSize"
          v-model:current-page="currentPage"
          :page-sizes="[8, 16, 32, 64]"
          @current-change="handlePageChange"
        />
      </div>
  </div>
</template>

<script setup lang="ts">
import { computed, onMounted, ref } from "vue";
import { ElMessage } from "element-plus";
import { useRouter } from "vue-router";
import {
  ActivityApplicationControllerService,
  type ActivityApplicationVO,
  ClubApplicationControllerService,
  type ClubApplicationVO,
  UserApplicationControllerService,
  ClubControllerService,
  ActivityControllerService,
  type UserApplicationVO,
} from "../../../../generated/index.ts";
import { useUserStore } from "../../../stores/user.ts";

interface PersonalApplication {
  id: number;
  typeCode: number;
  type: string;
  clubId: number;
  clubName: string;
  activityId: number;
  activityName: string;
  status: string;
  applyTime: string;
}

const applications = ref<PersonalApplication[]>([]);

// 获取状态对应的标签类型
const getStatusType = (status: string) => {
  switch (status) {
    case "待审核":
      return "warning";
    case "通过":
      return "success";
    case "拒绝":
      return "danger";
    default:
      return "info";
  }
};

const getApplicationType = (type: number): string => {
  switch (type) {
    case 0:
      return "账号注销";
    case 1:
      return "加入社团";
    case 2:
      return "退出社团";
    case 3:
      return "参加活动";
    case 4:
      return "退出活动";
    case 5:
      return "创建社团";
    case 6:
      return "注销社团";
    case 7:
      return "修改社团信息";
    case 8:
      return "举办活动";
    case 9:
      return "取消活动";
    case 10:
      return "修改活动信息";
    default:
      return "";
  }
};

const getApplicationLevel = (typeCode: number): string => {
  if (typeCode >= 0 && typeCode <= 4) return "个人";
  if (typeCode >= 5 && typeCode <= 7) return "社团";
  return "活动";
};

const getApplicationTypeColor = (type: string): string => {
  switch (type) {
    case "账号注销":
    case "注销社团":
    case "退出社团":
    case "退出活动":
    case "取消活动":
      return "danger";
    case "创建社团":
    case "加入社团":
    case "参加活动":
    case "举办活动":
      return "success";
    case "修改社团信息":
    case "修改活动信息":
      return "primary";
    default:
      return "info";
  }
};

const getTargetName = async (type: number, id: number): Promise<string> => {
    try {
      if (type ===0 || type === 1 || type === 2) {
        // 社团
        const res = await ClubControllerService.getClubVoById(id);
        if (res.code === 0) 
        return res.data?.clubName || '未知社团';
      } else if (type === 3 || type === 4) {
        // 活动
        const res = await ActivityControllerService.getActivityVoById(id);
        if (res.code === 0) return res.data?.activityName || '未知活动';
      }
      return '未知目标';
    } catch (e) {
      console.error('获取目标名称失败', e);
      return '加载失败';
    }
  };

const userStore = useUserStore();
const loadData = async () => {
  try {
    const userApplicationRes =
      await UserApplicationControllerService.listApplicationVoByPage({
        userId: userStore.id,
      });

    if (userApplicationRes.code === 0) {
      const userApplicationVoList = userApplicationRes.data
        ?.records as UserApplicationVO[];
        
      for (const userApplication of userApplicationVoList) {
        console.log("状态值：", userApplication.reviewVO?.result); // 打印状态值

        const applicationType = userApplication.type;

        if (applicationType === 0) {
          applications.value.push({
            id: userApplication.id as number,
            typeCode: userApplication.type as number,
            type: getApplicationType(userApplication.type as number) as string,
            status: userApplication.reviewVO?.result,
            applyTime: userApplication.createTime,
          } as PersonalApplication);

        } else if (applicationType === 1 || applicationType === 2) {
          const clubName = await getTargetName(applicationType, userApplication.additionalInfo as number);
          applications.value.push({
            id: userApplication.id as number,
            typeCode: userApplication.type as number,
            type: getApplicationType(userApplication.type as number) as string,
            clubId: userApplication.additionalInfo as number,
            clubName: clubName,
            activityName: "/",
            status: userApplication.reviewVO?.result,
            applyTime: userApplication.createTime,
          } as PersonalApplication);
          console.log("状态值：", userApplication.reviewVO?.result);
        } else if (applicationType === 3 || applicationType === 4) {
          const activityName = await getTargetName(applicationType, userApplication.additionalInfo as number);
          applications.value.push({
            id: userApplication.id as number,
            typeCode: userApplication.type as number,
            type: getApplicationType(userApplication.type as number) as string,
            activityId: userApplication.additionalInfo as number,
            clubName: "/",
            activityName: activityName,
            status: userApplication.reviewVO?.result,
            applyTime: userApplication.createTime,
          } as PersonalApplication);
        }
      }
    } else {
      ElMessage.error("加载数据时发生错误：" + userApplicationRes.message);
    }

    const clubApplicationRes =
      await ClubApplicationControllerService.listClubApplicationVoByPage({
        userId: userStore.id,
      });
    if (clubApplicationRes.code === 0) {
      const clubApplicatonVoList = clubApplicationRes.data
        ?.records as ClubApplicationVO[];
      for (const clubApplication of clubApplicatonVoList) {
        const type = clubApplication.type;
        if (type === 5) {
          applications.value.push({
            id: clubApplication.id as number,
            typeCode: clubApplication.type as number,
            type: getApplicationType(clubApplication.type as number) as string,
            clubId: clubApplication.clubVo?.id as number,
            clubName: clubApplication.clubName as string,
            status: clubApplication.reviewVO?.result|| "待审核",
            applyTime: clubApplication.createTime,
          } as PersonalApplication);
        } else {
          applications.value.push({
            id: clubApplication.id as number,
            typeCode: clubApplication.type as number,
            type: getApplicationType(clubApplication.type as number) as string,
            clubId: clubApplication.clubVo?.id as number,
            clubName: clubApplication.clubVo?.clubName as string,
            status: clubApplication.reviewVO?.result|| "待审核",
            applyTime: clubApplication.createTime,
          } as PersonalApplication);
        }
      }
    } else {
      ElMessage.error("加载数据时发生错误：" + clubApplicationRes.message);
    }

    const activityApplicationRes =
      await ActivityApplicationControllerService.listApplicationVoByPage1({
        userId: userStore.id,
      });
    if (activityApplicationRes.code === 0) {
      const activityApplicationVoList = activityApplicationRes.data
        ?.records as ActivityApplicationVO[];
      for (const activityApplication of activityApplicationVoList) {
        const type = activityApplication.type;
        if (type === 8) {
          applications.value.push({
            id: activityApplication.id as number,
            typeCode: activityApplication.type as number,
            type: getApplicationType(
              activityApplication.type as number,
            ) as string,
            activityId: activityApplication.activityVO?.id as number,
            activityName: activityApplication.additionalInfo
              ?.activityName as string,
            status: activityApplication.reviewVO?.result,
            applyTime: activityApplication.createTime,
          } as PersonalApplication);
        } else {
          applications.value.push({
            id: activityApplication.id as number,
            typeCode: activityApplication.type as number,
            type: getApplicationType(
              activityApplication.type as number,
            ) as string,
            activityId: activityApplication.activityVO?.id as number,
            activityName: activityApplication.activityVO
              ?.activityName as string,
            status: activityApplication.reviewVO?.result,
            applyTime: activityApplication.createTime,
          } as PersonalApplication);
        }
      }
    } else {
      ElMessage.error("加载数据时发生错误：" + activityApplicationRes.message);
    }
  } catch (error) {
    console.error("加载数据时发生错误:", error);
    ElMessage.error("加载数据时发生错误，请稍后重试");
  }
};

onMounted(() => {
  loadData();
});

// 定义申请类型筛选选项
const applicationTypeFilters = [
  { text: "账号注销", value: "账号注销" },
  { text: "加入社团", value: "加入社团" },
  { text: "退出社团", value: "退出社团" },
  { text: "参加活动", value: "参加活动" },
  { text: "退出活动", value: "退出活动" },
  { text: "创建社团", value: "创建社团" },
  { text: "注销社团", value: "注销社团" },
  { text: "修改社团信息", value: "修改社团信息" },
  { text: "举办活动", value: "举办活动" },
  { text: "取消活动", value: "取消活动" },
  { text: "修改活动信息", value: "修改活动信息" },
];

//筛选申请类型方法
const filterType = (value: string, row: PersonalApplication) => {
  return row.type === value;
};

// 定义状态筛选选项
const statusFilters = [
  { text: "待审核", value: "待审核" },
  { text: "通过", value: "通过" },
  { text: "拒绝", value: "拒绝" },
];

// 筛选审核状态方法
const filterStatus = (value: string, row: PersonalApplication) => {
  return row.status === value;
};

// 申请等级筛选项
const applicationLevelFilters = [
  { text: "个人", value: "个人" },
  { text: "社团", value: "社团" },
  { text: "活动", value: "活动" },
];

// 筛选申请等级方法
const filterApplicationLevel = (value: string, row: PersonalApplication) => {
  return getApplicationLevel(row.typeCode) === value;
};

// 按申请时间排序
const sortOrder = ref("descending");

const sortByApplyTime = () => {
  applications.value.sort((a, b) => {
    const timeA = new Date(a.applyTime).getTime();
    const timeB = new Date(b.applyTime).getTime();
    return sortOrder.value === "ascending" ? timeA - timeB : timeB - timeA;
  });
  sortOrder.value =
    sortOrder.value === "ascending" ? "descending" : "ascending";
};

// 分页相关
const currentPage = ref(1);
const pageSize = ref(10);
// const totalApplications = computed(() => applications.value.length);

const searchQuery = ref(""); // 搜索框的输入内容
const totalApplications = computed(() => filteredApplications.value.length);

// // 筛选逻辑（根据搜索关键词过滤）
// const filteredApplications = computed<PersonalApplication[]>(() => {
//   if (!searchQuery.value) {
//     return applications.value;
//   }

//   const query = searchQuery.value.toLowerCase();
//   return applications.value.filter((item) => {
//     return (
//       item.id.toString().includes(query) ||
//       (item.clubName && item.clubName.toLowerCase().includes(query)) ||
//       (item.activityName && item.activityName.toLowerCase().includes(query))
//     );
//   });
// });

// 分页逻辑（在筛选结果上分页）
const paginatedApplications = computed<PersonalApplication[]>(() => {
  const startIndex = (currentPage.value - 1) * pageSize.value;
  const endIndex = startIndex + pageSize.value;
  return filteredApplications.value.slice(startIndex, endIndex);
});

const handlePageChange = (page: number) => {
  currentPage.value = page;
};

const router = useRouter();
router.beforeEach((to, from, next) => {
  console.log("跳转到：", to.path);
  next(); // 确保允许跳转
});
// 处理详情按钮点击事件
const handleDetails = (row: PersonalApplication) => {
  let routePath = "";
  if (row.typeCode >= 0 && row.typeCode <= 4) {
    routePath = "/application/user/info";
  } else if (row.typeCode >= 5 && row.typeCode <= 7) {
    routePath = "/application/club/info";
  } else {
    routePath = "/application/activity/info";
  }
  router.push({
    path: routePath,
    query: { id: row.id },
  });
};


// 搜索功能
const searchId = ref(""); // 申请编号搜索框的输入内容
const searchClubName = ref(""); // 社团名搜索框的输入内容
const searchActivityName = ref(""); // 活动名搜索框的输入内容
const filteredApplications = computed<PersonalApplication[]>(() => {
  return applications.value.filter((item) => {
    const idMatch = searchId.value
      ? item.id.toString().includes(searchId.value)
      : true;
    const clubNameMatch = searchClubName.value
      ? item.clubName &&
        item.clubName.toLowerCase().includes(searchClubName.value.toLowerCase())
      : true;
    const activityNameMatch = searchActivityName.value
      ? item.activityName &&
        item.activityName
          .toLowerCase()
          .includes(searchActivityName.value.toLowerCase())
      : true;

    return idMatch && clubNameMatch && activityNameMatch;
  });
});


// 重置搜索
const resetSearch = () => {
  searchId.value = ""; // 清空申请编号搜索框
  searchClubName.value = ""; // 清空社团名搜索框
  searchActivityName.value = ""; // 清空活动名搜索框
  currentPage.value = 1; // 重置到第一页
}; 
// 搜索功能
const searchApplications = () => {
  searchQuery.value = ""; // 清空搜索框
  currentPage.value = 1; // 重置到第一页
};


// 导出功能
import * as XLSX from 'xlsx';

const exportToExcel = () => {
  if (!applications.value.length) {
    ElMessage.warning('没有可导出的数据');
    return;
  }

  // 提取你想要导出的字段
  const exportData = applications.value.map((item) => ({
    '申请编号': item.id,
    '申请类型': item.type,
    '所属社团': item.clubName || '无',
    '活动名称': item.activityName || '无',
    '申请状态': item.status || '未知',
    '申请时间': item.applyTime ? new Date(item.applyTime).toLocaleString() : '未知',
  }));

  const worksheet = XLSX.utils.json_to_sheet(exportData);
  const workbook = XLSX.utils.book_new();
  XLSX.utils.book_append_sheet(workbook, worksheet, '申请信息');

  // 下载 Excel 文件
  XLSX.writeFile(workbook, `申请信息列表_${new Date().toISOString().slice(0, 10)}.xlsx`);
};



</script>

<style scoped>
.user-personal-applications {
  width: 100%; /* 或者指定一个具体的宽度值，如 90% 或 800px */
  max-width: 1200px; /* 可选：设置最大宽度以防止内容溢出屏幕 */
  margin: 0 auto; /* 如果需要居中显示 */
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
.el-tabel {
  width: 100%;
}
.pagination-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 20px;

  .record-count {
    font-size: 14px;
    color: #666;
  }

  el-pagination {
    margin-left: auto;
  }
}
.search-section {
  display: flex;
  align-items: center;
  margin-bottom: 20px;

  .el-input {
    margin-right: 10px;
  }

  .el-button {
    margin-right: 10px;
  }
}
</style>
